package cn.devhost;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author shenguangyang
 */
@Slf4j
public class NetworkUtils {
    public static List<NetworkInfo> getNetWorkInfo(List<String> networkInterfaceList) throws Exception {
        List<NetworkInfo> resultList = new ArrayList<>();
        if (CollUtil.isNotEmpty(networkInterfaceList)) {
            networkInterfaceList.forEach(item -> {
                try {
                    String ip = getLinuxLocalIp(item);
                    resultList.add(NetworkInfo.builder().interfaceName(item).ip(ip).build());
                    if (StrUtil.isNotEmpty(ip)) {
                        log.info("{} : {}", item, ip);
                    }
                } catch (Exception e) {
                    log.error("获取网卡信息失败, networkInterface: {}, error: ", item, e);
                }
            });
        }
        return resultList;
    }

    /**
     * 获取Linux下的IP地址
     *
     */
    private static String getLinuxLocalIp(String findName) throws Exception {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface net = en.nextElement();
                String name = net.getName(); // 这里指定ip 先执行一下看看需要选择的IP
                if (name.equals(findName)) {
                    for (Enumeration<InetAddress> enumIpAddr = net.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            log.error("error: ", ex);
            return "获取ip地址异常 - " + ex.getMessage();
        }
        return ip;
    }
}
